﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;
using DHQGHN.DAL;
using DHQGHN.DAL.BO.TDT;
using DHQGHN.DAL.Models.TDT;

namespace DHQGHN.Services.TDT
{
    public class EnumeratorService : IEnumeratorService
    {
        private EnumeratorBO enumeratorBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(EnumeratorService));
        public EnumeratorService()
        {
            enumeratorBO = new EnumeratorBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_TDT_CONNECTION_STRING);
        }

        public DAL.Models.TDT.Enumerator GetByID(string enumeratorID)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new Enumerator();
                }
                else
                {
                    if (string.IsNullOrEmpty(enumeratorID))
                    {
                        Fault.ValidationFault fault = new Fault.ValidationFault()
                        {
                            Result = false,
                            Message = "Thiếu tham số",
                            Description = "Thiếu tham số"
                        };

                        throw new FaultException<Fault.ValidationFault>(fault);
                    }

                    return enumeratorBO.GetByID(enumeratorID);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                   new Fault.UnexpectedServiceFault
                   {
                       ErrorMessage = ex.Message,
                       Source = ex.Source,
                       Target = ex.TargetSite.ToString(),
                       StackTrace = ex.StackTrace
                   },
                   new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public IEnumerable<DAL.Models.TDT.Enumerator> GetAll()
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Enumerator>();
                }
                else
                {
                    return enumeratorBO.GetAll();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception"))
               );
            }
        }

        public IEnumerable<Enumerator> GetByAdminCode(string adminCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Enumerator>();
                }
                else
                {
                    return enumeratorBO.GetByAdminCode(adminCode);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace

                    }, new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public DAL.Models.TDT.Enumerator GetByEnumCode(string enumCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new Enumerator();
                }
                else
                {
                    return enumeratorBO.GetByEnumCode(enumCode);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace

                    }, new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public void AddEnumerator(DAL.Models.TDT.Enumerator enumerator)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    int saveState = 0;
                    enumeratorBO.Save(enumerator, flag: saveState);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception"))
               );
            }
        }

        public void DeleteEnumerator(DAL.Models.TDT.Enumerator enumerator)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    enumeratorBO.Delete(enumerator.ENUMERATOR_ID);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        public int Checkadminunit(string valuecom, string value, string level)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return 0;
                }
                else
                {
                    return enumeratorBO.Checkadminunit(valuecom, value, level);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public void EditEnumerator(DAL.Models.TDT.Enumerator enumerator)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    int updateState = 1;
                    enumeratorBO.Save(enumerator, flag: updateState);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                   new Fault.UnexpectedServiceFault
                   {
                       ErrorMessage = ex.Message,
                       Source = ex.Source,
                       Target = ex.TargetSite.ToString(),
                       StackTrace = ex.StackTrace
                   },
                   new FaultReason(string.Format("{0}", "Service fault exception")));

            }
        }

        public IEnumerable<DAL.Models.TDT.Enumerator> SearchBy(SearchEnumerator info)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Enumerator>();
                }
                else
                {
                    return enumeratorBO.SearchBy(info);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                   new Fault.UnexpectedServiceFault
                   {
                       ErrorMessage = ex.Message,
                       Source = ex.Source,
                       Target = ex.TargetSite.ToString(),
                       StackTrace = ex.StackTrace
                   },
                   new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        /// <summary>
        /// phunx1, 20150613: method lay thong tin chung nguoi dung sau khi dang nhap he thong
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Enumerator GetInfoByUserName(string userName)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new Enumerator();
                }
                else
                {
                    return enumeratorBO.GetInfoByUserName(userName);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace

                    }, new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        /// <summary>
        /// datlq, 20150619, lay theo admincode va groupcode
        /// </summary>
        /// <param name="enumCode"></param>
        /// <returns></returns>
        public List<Enumerator> GetByAdminGroupCode(SearchEnumerator obj)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Enumerator>();
                }
                else
                {
                    return enumeratorBO.GetByAdminGroupCode(obj);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace

                    }, new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public DAL.JSONMessage UpdateSignature(DAL.ModelsUpload.ENUMERATOR_UPLOAD_SIGNATURE enumerator)
        {
            JSONMessage jsonReturn = new JSONMessage();

            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    jsonReturn.ErrorCode = -1;
                    jsonReturn.ErrorMessage = Properties.Resources.MSG_ERROR;
                }
                else
                {
                    if (enumerator != null && enumerator.ENUMERATOR_ID != null)
                    {
                        jsonReturn.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                        jsonReturn.ID = enumerator.ENUMERATOR_ID;

                        if (DHQGHN.Common.Utils.IsNullOrEmptyOverride(enumerator.ENUMERATOR_ID))
                        {
                            jsonReturn.ErrorCode = -1;
                            jsonReturn.ErrorMessage = Properties.Resources.MSG_LOST_PARAMETTER;
                        }
                        else if (DHQGHN.Common.Utils.IsNullOrEmptyOverride(enumerator.SIGNATURE))
                        {
                            jsonReturn.ErrorCode = -1;
                            jsonReturn.ErrorMessage = Properties.Resources.MSG_LOST_PARAMETTER;
                        }
                        else
                        {
                            bool res = enumeratorBO.UpdateSignature(enumerator);
                            if (res)
                            {
                                jsonReturn.ErrorCode = 200;
                                jsonReturn.ErrorMessage = Properties.Resources.MSG_SUCCESS;
                            }
                            else
                            {
                                jsonReturn.ErrorCode = -1;
                                jsonReturn.ErrorMessage = Properties.Resources.MSG_ERROR;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace

                    }, new FaultReason(string.Format("{0}", "Service fault exception")));
            }
            return jsonReturn;
        }

        public List<Enumerator> SearchPagingBy(SearchEnumerator info)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Enumerator>();
                }
                else
                {
                    return enumeratorBO.SearchPagingBy(info);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                   new Fault.UnexpectedServiceFault
                   {
                       ErrorMessage = ex.Message,
                       Source = ex.Source,
                       Target = ex.TargetSite.ToString(),
                       StackTrace = ex.StackTrace
                   },
                   new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public List<Enumerator> SearchPagingForAdmin(SearchEnumerator info)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Enumerator>();
                }
                else
                {
                    return enumeratorBO.SearchPagingForAdmin(info);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                   new Fault.UnexpectedServiceFault
                   {
                       ErrorMessage = ex.Message,
                       Source = ex.Source,
                       Target = ex.TargetSite.ToString(),
                       StackTrace = ex.StackTrace
                   },
                   new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public EnumeratorDeleteInfo Delete(SearchEnumerator info)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new EnumeratorDeleteInfo();
                }
                else
                {
                    enumeratorBO.Delete(info.ENUMERATOR_ID);
                    List<Enumerator> data = SearchPagingBy(info);
                    int pageIndex = int.Parse(info.PAGE_INDEX);
                    int recordCount = 0;
                    if (data.Count<Enumerator>() == 0)
                    {
                        if (pageIndex > 0)
                        {
                            pageIndex--;
                        }
                    }
                    else recordCount = data[0].RECORD_COUNT;

                    return new EnumeratorDeleteInfo() { PageIndex = pageIndex, RecordCount = recordCount };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
    }
}